package com.wxq.koland.xiaoliscan;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.widget.TextView;
import android.widget.Toast;

import com.wxq.koland.xiaoliscan.bean.NormalBean;
import com.wxq.koland.xiaoliscan.bean.UserInfo;
import com.wxq.koland.xiaoliscan.network.RequestUtils;
import com.wxq.koland.xiaoliscan.utils.ActivityUtil;
import com.wxq.koland.xiaoliscan.utils.LogUtil;
import com.wxq.koland.xiaoliscan.utils.NetworkUtil;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import cn.bingoogolapple.qrcode.core.QRCodeView;
import cn.bingoogolapple.qrcode.zxing.ZXingView;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class MainActivity extends Activity implements QRCodeView.Delegate {


    private static final int MY_PERMISSIONS_REQUEST = 8;
    String[] permissions = new String[]{
            Manifest.permission.CAMERA,
            Manifest.permission.WRITE_EXTERNAL_STORAGE
    };
    @BindView(R.id.zxingview)
    ZXingView zxingview;
    @BindView(R.id.text)
    TextView text;


    private String mac;
    private List<String> permissionsList = new ArrayList<>();


    @Override
    protected void onCreate (Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);
        checkPermissions();
        mac = NetworkUtil.getMacFromHardware();
        LogUtil.d("onCreate mac--->" + mac);
    }

    @Override
    protected void onStart () {
        super.onStart();
        zxingview.startCamera();
        zxingview.startSpotAndShowRect();
        timer.start();
        LogUtil.d("onStart");
    }

    //检查权限
    private void checkPermissions () {
        permissionsList.clear();
        for (int i = 0; i < permissions.length; i++) {
            if (ContextCompat.checkSelfPermission(MainActivity.this, permissions[i]) != PackageManager.PERMISSION_GRANTED) {
                permissionsList.add(permissions[i]);

                LogUtil.d("checkPermissions:" + permissions[i]);
            }
        }
        if (permissionsList.isEmpty()) {//未授予的权限为空，表示都授予了
            init();
            LogUtil.d("checkPermissions:全部授权");
        } else {
            //请求权限方法
            String[] permissions = permissionsList.toArray(new String[permissionsList.size()]);//将List转为数组
            ActivityCompat.requestPermissions(MainActivity.this, permissions, MY_PERMISSIONS_REQUEST);
            LogUtil.d("checkPermissions：去请求");
        }
    }

    //权限回调
    @Override
    public void onRequestPermissionsResult (int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        if (requestCode == MY_PERMISSIONS_REQUEST) {
            for (int i = 0; i < grantResults.length; i++) {
                if (grantResults[i] != PackageManager.PERMISSION_GRANTED) {
                    //判断是否勾选禁止后不再询问
                    boolean showRequestPermission = ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this, permissions[i]);
                    if (showRequestPermission) {
                        Toast.makeText(this, "权限未申请", Toast.LENGTH_SHORT).show();

                    }
                }
            }

            checkPermissions();
        }
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }

    //二维码初始化
    private void init () {
        zxingview.setDelegate(this);
        LogUtil.d("init");
    }


    @Override
    public void onScanQRCodeSuccess (String result) {
        LogUtil.d("结果回调：result--" + result + "  mac--" + mac);
        //网络请求数据
        RequestUtils.postUser(result, mac, new Callback<UserInfo>() {
            @Override
            public void onResponse (Call<UserInfo> call, Response<UserInfo> response) {
                if (response.isSuccessful()) {
                    LogUtil.e("body:" + response.body().toString() + "   code:" + response.code());
                    if (response.body().getCode() == 1) {
                        text.setText("请对准摄像头，出示您的二维码");
                        goShowInfo(response.body().getData());
                    }  else {
                        text.setText(response.body().getMsg());
                    }
                } else {
                    Toast.makeText(MainActivity.this, "扫码失败，请重新扫码！", Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onFailure (Call<UserInfo> call, Throwable t) {
                LogUtil.e("回调失败");
                text.setText("网络请求失败！");

                Toast.makeText(MainActivity.this, "扫码失败，请重新扫码！", Toast.LENGTH_SHORT).show();
            }
        });
    }

    @Override
    public void onCameraAmbientBrightnessChanged (boolean isDark) {

    }

    @Override
    public void onScanQRCodeOpenCameraError () {
        LogUtil.d("结果回调：error");
        zxingview.startSpotAndShowRect();
    }


    CountDownTimer timer = new CountDownTimer(30 * 1000, 3 * 1000) {
        @Override
        public void onTick (long millisUntilFinished) {
            zxingview.startSpot();
            LogUtil.d("timer------->" + (millisUntilFinished / 1000));
            if (!text.getText().toString().equals("请对准摄像头，出示您的二维码")){
                text.setText("请对准摄像头，出示您的二维码");
            }
        }

        @Override
        public void onFinish () {
            finishALL();
        }
    };

    private void finishALL () {
        if (timer != null) {
            timer.cancel();
            timer = null;
            this.finish();
            ActivityUtil.getInstance().exitSystem();
        }
    }

    private void goShowInfo (UserInfo.DataBean result) {
        Intent intent = new Intent();
        intent.setClass(this, ShowInfoActivity.class);
        Bundle bundle = new Bundle();
        bundle.putString("userName", result.getUsername());
        bundle.putString("phone", result.getPhone());
        bundle.putInt("set", result.getSex());
        bundle.putString("temperature", result.getTemperature());
        bundle.putInt("count", result.getCount());
        intent.putExtra("userInfo", bundle);
        startActivity(intent);
    }

    @Override
    protected void onStop () {
        super.onStop();
        zxingview.stopCamera();
        timer.cancel();
        LogUtil.d("onStop");
    }

    @Override
    protected void onDestroy () {
        super.onDestroy();
        zxingview.onDestroy();
    }
}
